/**
 * Copyright (c) 2007-2008 Nearchos Paspallis
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * AspectSense
 *
 * Middleware for annotation-based, context-aware and adaptive services for
 * mobile and ubiquitous computing
 *
 * This project is an open-source effort, initiated by Nearchos Paspallis as
 * part of his PhD work at the University of Cyprus (http://www.ucy.ac.cy).
 *
 * More information about the project is available at "http://aspectsense.org".
 */

package org.aspectsense.framework;

import org.aspectsense.classloaders.JarsClassLoader;
import org.aspectsense.classloaders.DefaultJarsClassLoader;
import org.aspectsense.classloaders.JarsClassLoaderException;
import org.aspectsense.metadata.MetadataFactory;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.jar.JarFile;
import java.util.jar.JarEntry;
import java.util.Enumeration;

/**
 * todo: at some point i might have to define a dynamic class loader to enable uninstalling of components
 *
 * @author Nearchos Paspallis [nearchos@cs.ucy.ac.cy]
 *         Date: Dec 17, 2007
 *         Time: 12:44:04 PM
 */
class PackageManager
{
    private final Logger logger =
            Logger.getLogger(PackageManager.class.getCanonicalName());

    private final Repository repository = Repository.getInstance();

    private final JarsClassLoader jarsClassLoader;

   // ----------------- Singleton pattern implementation ------------------- //

   private static PackageManager instance = null;

   /**
    * Provides access to the lazy-loaded singleton instance of the
    * {@link Repository}.
    *
    * @return an instance of {@link Repository}
    */
   public static PackageManager getInstance()
   {
       synchronized(PackageManager.class)
       {
           if(instance == null) instance = new PackageManager();

           return instance;
       }
   }

   private PackageManager()
   {
       logger.fine("Starting instance of " + PackageManager.class.getCanonicalName());

       jarsClassLoader = DefaultJarsClassLoader.createDefaultJarsClassLoader();
//       jarsClassLoader = UrlJarsClassLoader.createUrlClassLoader();

       logger.fine("Selected JarsClassLoader: " + jarsClassLoader);
   }

   // --------------- End of singleton pattern implementation -------------- //

    /**
     *
     * @param file the file to be installed
     */
    void installPackage(final File file)
    {
        if(file == null)
        {
            throw new NullPointerException("Invalid null argument");
        }

        if(!file.exists())
        {
            throw new IllegalArgumentException("The specified file does not exist: " + file);
        }

        if(file.isDirectory())
        {
            throw new IllegalArgumentException("The specified file is an argument: " + file);
        }

        if(!file.getName().toLowerCase().endsWith(".jar"))
        {
            throw new IllegalArgumentException("The specified file is not of type JAR archive: " + file);
        }

        // first step is to load the included classes in the class loader
        try
        {
            jarsClassLoader.addJarFile(file);
        }
        catch (JarsClassLoaderException jcle)
        {
            throw new RuntimeException(jcle);
        }

        try
        {
            final JarFile jarFile = new JarFile(file);
            final Enumeration<JarEntry> jarEntries = jarFile.entries();

            while(jarEntries.hasMoreElements())
            {
                final JarEntry jarEntry = jarEntries.nextElement();

                // process embedded classes/components
                if(!jarEntry.isDirectory() && jarEntry.getName().toLowerCase().endsWith(".class"))
                {
                    String className = jarEntry.getName().replace('/', '.').substring(0, jarEntry.getName().length() - 6);

                    try
                    {
                        Class clazz = jarsClassLoader.loadClass(className);

                        // check if class is component or service
                        if(MetadataFactory.isComponent(clazz))
                        {
                            logger.finest("Detected component in class: " + className);
                            repository.installComponent(clazz);
                        }
                    }
                    catch (ClassNotFoundException cnfe)
                    {
                        throw new RuntimeException("Could not detect the" +
                                " included class in the JarsClassLoader: " +
                                className, cnfe);
                    }
                    catch (InstallationException ie)
                    {
                        // todo handle?
                        throw new RuntimeException(ie);
                    }
                }
            }
        }
        catch (IOException ioe)
        {
            throw new RuntimeException(ioe);
        }
    }

    /**
     *
     * @param file the file to be uninstalled
     */
    void uninstallPackage(final File file)
    {
        if(file == null)
        {
            throw new NullPointerException("Invalid null argument");
        }

        throw new UnsupportedOperationException();
        // todo
    }
}